package com.inspiration.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.cell.CellEditor;
import cn.hutool.poi.excel.cell.CellUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.inspiration.dao.CategoryContentRelationMapper;
import com.inspiration.dao.CategoryMapper;
import com.inspiration.dao.ContentMapper;
import com.inspiration.dao.TagContentRelationMapper;
import com.inspiration.dao.TagMapper;
import com.inspiration.entity.Category;
import com.inspiration.entity.CategoryContentRelation;
import com.inspiration.entity.Content;
import com.inspiration.entity.Page;
import com.inspiration.entity.R;
import com.inspiration.entity.Tag;
import com.inspiration.entity.TagContentRelation;
import com.inspiration.entity.dto.ContentDTO;
import com.inspiration.entity.dto.SearchContentDTO;
import com.inspiration.entity.vo.ContentVO;
import com.inspiration.entity.vo.TagVO;
import com.inspiration.service.CategoryService;
import com.inspiration.service.ContentService;
import com.inspiration.service.TagService;
import com.inspiration.utils.ArraysUtils;
import com.inspiration.utils.PathUtils;
import lombok.SneakyThrows;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.FormulaError;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.NumberToTextConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author Vincent.jiao
 * @Date 2023/10/24 12:00
 */
@RestController
@RequestMapping("/content")
public class ContentController {
    @Autowired
    TagContentRelationMapper tagContentRelationMapper;

    @Autowired
    CategoryContentRelationMapper categoryContentRelationMapper;

    @Autowired
    CategoryService categoryService;

    @Autowired
    TagService tagService;

    @Autowired
    ContentService contentService;

    /**
     *
     * @param
     */
    @RequestMapping("/insert")
    public Object insert(@RequestBody ContentDTO contentDTO) {
        return contentService.writeContent(contentDTO);
    }

    /**
     *
     * @param content
     */
    @RequestMapping("/update")
    public Object update(@RequestBody ContentDTO contentDTO) {
        return contentService.writeContent(contentDTO);
    }

    /**
     * del
     */
    @RequestMapping("/del")
    public Object del(Long cId    ) {
        return contentService.del(cId);
    }

    @RequestMapping("count")
    public Object count() {
        int counteNum = contentService.count();
        int categoryNum = categoryService.count();
        int tagNum = tagService.countAll();

        Map<String, Object> map = R.ok("contentNum", counteNum);
         map.put("categoryNum", categoryNum);
         map.put("tagNum", tagNum);
        return map;
    }

    @RequestMapping("one")
    public Object one(Long cId) {
        ContentVO contentVO = new ContentVO();
        Content content = contentService.getById(cId);
        BeanUtil.copyProperties(content, contentVO);

        List<TagContentRelation> relationList = tagContentRelationMapper.selectList(new LambdaQueryWrapper<TagContentRelation>().eq(TagContentRelation::getTcr_c_id, cId));
        List<Long> idList = relationList.stream().map(TagContentRelation::getTcr_t_id).collect(Collectors.toList());
        contentVO.setTagIdList(idList);

        List<CategoryContentRelation> relationList2 =  categoryContentRelationMapper.selectList(new LambdaQueryWrapper<CategoryContentRelation>().eq(CategoryContentRelation::getCcr_content_id, cId));;
        idList = relationList2.stream().map(CategoryContentRelation::getCcr_category_id).collect(Collectors.toList());
        contentVO.setCategoryIdList(idList);

        return contentVO;
    }

    @RequestMapping("search")
    public Object  search(SearchContentDTO contentDTO ) {
        if(StrUtil.isNotEmpty(contentDTO.getCName())){
            contentDTO.setCName("%"+contentDTO.getCName().trim()+"%");
        }

        PageHelper.startPage(contentDTO.getPageNo(), contentDTO.getPageSize(), " c_id  desc ");
        PageInfo pageInfo = new PageInfo(contentService.listBySearchContentDTO(contentDTO));
        List<Long> idList = pageInfo.getList();
        List<ContentVO> list = new LinkedList<>();

        //组装数据与排序
        if(CollUtil.isNotEmpty(idList)){
            List<ContentVO> tmpList = contentService.listDetailsVO(idList);
            Map<Long, ContentVO> tmpMap = new HashMap<>();
            for (ContentVO contentVO : tmpList) {
                List<TagVO> result = new LinkedList<>();
                if(CollUtil.isNotEmpty(contentVO.getTagList())) {
                    for (TagVO tagVO : contentVO.getTagList()) {
                        tagVO.setContentCount( tagService.contentCount(tagVO.getT_id()));
                        result.add(tagVO);
                    }
                }

                tmpMap.put(contentVO.getC_id(), contentVO);
            }

            //按排序顺序放好
            for (Long id : idList) {
                list.add(tmpMap.get(id));
            }
        }
        pageInfo.setList(list);


        return new Page(pageInfo);
    }

    @RequestMapping("import")
    @Transactional
    public Object importExcel(@RequestParam("file") MultipartFile file) throws IOException {
        Workbook workbook = ExcelUtil.getReader(file.getInputStream()).getWorkbook();
        return contentService.importExcel(workbook);
    }

    @SneakyThrows
    @RequestMapping("/upload")
    public Object upload(@RequestParam("imgFile") MultipartFile multipartFile) {
        Map<String, Object> map = null;

        if(multipartFile == null){
            map = R.fail("error", 1);
            map.put("message", "请上传图片");

            return map;
        }

        File uplaodParentFile = new File(PathUtils.getFilePath());
        if(!uplaodParentFile.exists()) {
            uplaodParentFile.mkdirs();
        }

        File save = new File(uplaodParentFile, new Date().getTime() +"." + FileUtil.getSuffix(multipartFile.getOriginalFilename()));
        multipartFile.transferTo(save);

        String wbePath = save.getPath().replace(PathUtils.getLocalhostRoot(), "");
        wbePath = wbePath.replace('\\', '/');
        wbePath = wbePath.startsWith("/") ? wbePath : "/" + wbePath;

        map = R.fail("error", 0);
        map.put("url", wbePath);
        return map;
    }
}






























